
package com.epam.android.training.day10.task1;

import com.epam.android.training.day10.task1.Contacts.PersonalData;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Main activity shows list of contacts from database. Initiates new contact
 * creation, editing existed contacts or remove them from database.
 * 
 * @author Anton Novikau
 */
public class ContactsList extends Activity {

  private static final String[] PROJECTION = {
      PersonalData._ID, PersonalData.FIRST_NAME, PersonalData.LAST_NAME
  };

  private ListView contactsContainer;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    contactsContainer = (ListView) findViewById(R.id.contacts);

    populateContacts();

    addCreateNewButtonAction();

    addDeleteButtonAction();

    addEditContactAction();
  }

  /**
   * Populates contacts list view with data from {@link Contacts.PersonalData}
   * table.
   */
  private void populateContacts() {
    Cursor resultSet = managedQuery(PersonalData.CONTENT_URI, PROJECTION, null, null, null);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_item, resultSet,
        new String[] {
            PersonalData.FIRST_NAME, PersonalData.LAST_NAME
        }, new int[] {
            R.id.first_name_item, R.id.last_name_item
        });
    contactsContainer.setAdapter(adapter);
  }

  /**
   * Adds action to "create new contact" button. Must start
   * {@link ContactEditor} activity in create new mode.
   */
  private void addCreateNewButtonAction() {
    Button addNewButton = (Button) findViewById(R.id.add_new);
    addNewButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        startActivity(new Intent(Intent.ACTION_INSERT, PersonalData.CONTENT_URI));
      }
    });
  }

  /**
   * Adds action edit on list view item click. Must start {@link ContactEditor}
   * activity in edit mode.
   */
  private void addEditContactAction() {
    contactsContainer.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Uri uri = ContentUris.withAppendedId(PersonalData.CONTENT_URI, id);
        startActivity(new Intent(Intent.ACTION_EDIT, uri));
      }
    });
  }

  /**
   * Adds action to "delete" button. Must delete selected with check boxe
   * contacts from database.
   */
  private void addDeleteButtonAction() {
    Button deleteButton = (Button) findViewById(R.id.delete);
    deleteButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // find all checked items.
        List<Long> checkedIds = new ArrayList<Long>();
        int childCount = contactsContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
          View item = contactsContainer.getChildAt(i);
          CheckBox checkBox = (CheckBox) item.findViewById(R.id.checked_item);
          if (checkBox.isChecked()) {
            checkedIds.add(contactsContainer.getItemIdAtPosition(i));
          }
          // clear all selections
          checkBox.setChecked(false);
        }

        if (checkedIds.size() > 0) {
          // construct where clause for deletion if at least one item checked.
          StringBuilder where = new StringBuilder(PersonalData._ID);
          where.append(" IN (");
          // append ids to delete.
          String delimiter = ",";
          for (long id : checkedIds) {
            where.append(id).append(delimiter);
          }
          // remove last delimiter.
          where.deleteCharAt(where.lastIndexOf(delimiter));
          // append right paranthasis to the end of where clause.
          where.append(")");
          getContentResolver().delete(PersonalData.CONTENT_URI, where.toString(), null);
        } else {
          // show notification if no items were checked.
          Toast.makeText(ContactsList.this, R.string.contacts_not_checked_message,
              Toast.LENGTH_SHORT).show();
        }
      }
    });
  }
}
